import { useCallback, useEffect, useMemo } from 'react';
import { Route as RT } from '@ant-design/pro-layout/lib/typings';
import * as icons from '@ant-design/icons';

// 递归解析和转化路由配置（n级），生成面包屑路径，并且存入可用路由（1级）
const parseRoutes = (rs: RT[], availRoutes: RT[], parent: RT | null = null) => {
  rs.forEach((r) => {
    if (r.component) {
      if (!r.breadcrumb) {
        // 生成面包屑路径
        r.breadcrumb = [];
        if (parent && parent.breadcrumb) {
          // 继承parent的面包屑
          r.breadcrumb.push(...parent.breadcrumb);
        }
        r.breadcrumb.push(r);
        r.breadcrumbName = r.name;
      }
      // 有component属性，作为可访问路由
      availRoutes.push(r);
    }
    if (r.routes) {
      parseRoutes(r.routes, availRoutes, r);
    }
    // 转换icon，支持anticon和url
    if (r.icon && typeof r.icon === 'string') {
      if (r.icon.startsWith('http://') || r.icon.startsWith('https://')) {
        r.icon = <img src={r.icon} alt='' style={{ width: '1em', height: '1em' }} className='anticon' />;
      } else {
        // @ts-ignore
        const IconComp = icons[r.icon];
        r.icon = <IconComp />;
      }
    }
  });
};

/** use解析后的路由和可用路由 */
export const useParsedRoutes = (rs: RT[]) => {
  return useMemo(() => {
    const availRoutes: RT[] = [];
    parseRoutes(rs, availRoutes);
    return [rs, availRoutes] as [RT[], RT[]];
  }, [rs]);
};

/** use指定路径名的路由对象 */
export const useRouteByPath = (rs: RT[], pathname: string) => {
  const [, avail] = useParsedRoutes(rs);
  return avail.find((v) => v.path === pathname);
};
